package top.huhuiyu.springboot2.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.huhuiyu.springboot2.dao.TbNewsMapper;
import top.huhuiyu.springboot2.entity.*;
import top.huhuiyu.springboot2.service.NewsService;

import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {
  @Autowired
  private TbNewsMapper tbNewsMapper;

  @Override
  public BaseResult delete(Integer id) {
    tbNewsMapper.delete(id);
    BaseResult result = new BaseResult();
    result.setCode(200);
    result.setMessage("删除成功");
    result.setSuccess(true);
    return result;
  }

  @Override
  public BaseResult modify(TbNews news) {
    int i = tbNewsMapper.update(news);
    BaseResult result = new BaseResult();
    if (i == 1) {
      result.setMessage("修改成功");
      result.setSuccess(true);
      result.setCode(200);
    } else {
      result.setMessage("修改失败");
      result.setSuccess(false);
      result.setCode(500);
    }
    return result;
  }

  @Override
  public BaseDataResult<TbNews> queryByKey(Integer id) {
    TbNews tbNews = tbNewsMapper.queryByKey(id);
//    BaseDataResult<TbNews> result = new BaseDataResult<>();
    if (tbNews == null) {
//      result.setMessage("没有找到对应的数据");
//      result.setSuccess(false);
//      result.setCode(500);
      return BaseDataResult.fail("没有找到对应的数据", TbNews.class);
    } else {
      // 查询成功就要更新点击量
      tbNewsMapper.updateHits(id);
//      result.setData(tbNews);
//      result.setSuccess(true);
//      result.setCode(200);
      return BaseDataResult.ok(tbNews);
    }
//    return result;
  }


  @Override
  public BaseResult add(TbNews news) {
    int i = tbNewsMapper.add(news);
//    BaseResult result = new BaseResult();
    if (i == 1) {
//      result.setMessage("添加成功");
//      result.setSuccess(true);
//      result.setCode(200);
      return BaseResult.ok("添加成功");
    } else {
//      result.setMessage("添加失败");
//      result.setSuccess(false);
//      result.setCode(500);
      return BaseResult.fail("添加失败");
    }
//    return result;
  }

  @Override
  public BaseDataResult<PageResult<List<TbNews>>> query(NewsQuery query, PageBean page) {
    // 开启分页查询，必须是查询的方法的上一行
    // 开启后会自动执行统计记录数的语句
    // 还会自动将查询语句转换带limit的分页语句
    PageHelper.startPage(page.getPageNumber(), page.getPageSize());
    // 查询的返回值会自动改为带分页信息的对象
    Page<TbNews> list = (Page<TbNews>) tbNewsMapper.queryAll(query);
    BaseDataResult<PageResult<List<TbNews>>> result = new BaseDataResult<>();
    result.setCode(200);
    result.setSuccess(true);
    // getTotal获取总记录数,getResult获取分页查询结果
    page.setTotal(list.getTotal());
    result.setData(new PageResult<>(page, list.getResult()));
    return result;
  }

}
